from django.shortcuts import render
from rest_framework.generics import ListAPIView
from rest_framework.filters import OrderingFilter

from .models import SKU
from .serializers import SKUSerializer


# /categories/(?P<category_id>\d+)/skus?page=xxx&page_size=xxx&ordering=xxx
class SKUListView(ListAPIView):
    """商品列表分页:分页和排序"""

    # 指定查询集:需要展示的列表数据,需要根据条件过滤,category_id需要对应,还有必须是未下架的商品
    # queryset = SKU.objects.all()

    # 指定序列化器
    serializer_class = SKUSerializer

    # 指定分页(这种写法,只对这个视图的分页有效)
    # pagination_class = "自定义的分页类,自己执行分页规则"

    # 指定排序和过滤的后端:ordering=price(根据价格从小到大) ordering=-price(根据价格从大到小)
    filter_backends = [OrderingFilter]
    # 指定排序和过滤的字段:create_time=根据记录的时间排序,price=根据价格排序,sales=根据销量排序
    ordering_fields = ("create_time", "price", "sales")

    def get_queryset(self):
        """根据条件筛选出需要展示在列表界面的数据"""
        # category_id写在了视图中,所以获取方式是self.kwargs.get("category_id"),
        # 而不是self.context["view"].kwargs["category_id"]
        category_id = self.kwargs.get("category_id")
        return SKU.objects.filter(category_id=category_id, is_launched=True)